package com.hxzy.module.auth.controller;

import com.hxzy.framework.common.constant.CaptchaConstant;
import com.hxzy.framework.common.constant.RedisConstant;
import com.hxzy.framework.common.req.CaptchaCodeReq;
import com.hxzy.framework.common.resp.CaptchaCodeResp;
import com.hxzy.framework.common.resp.R;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author wy
 * @Description TODO
 * @Date 2024/1/26 16:34
 * @Version 1.0
 */
@Log4j2
@RestController
@Tag(name = "授权认证-easycaptcha验证码")
@RequestMapping("/easy")
public class EasyCaptchaController {

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value  = "图片验证码")
    @GetMapping(value = "/captcha")
    public R<CaptchaCodeResp> captcha(CaptchaCodeReq req){
        Captcha captcha=null;

        if(CaptchaConstant.PNG.equals( req.getType())){
            captcha=new SpecCaptcha(req.getWidth(), req.getHeight());
        }else if(CaptchaConstant.GIF.equals(req.getType())){
            captcha=new GifCaptcha(req.getWidth(), req.getHeight());
        }else{
            captcha= new ArithmeticCaptcha(req.getWidth(),req.getHeight());
        }
        captcha.setLen(req.getCodeCount());
        //验证码的结果
        String value = captcha.text();
        //令牌
        String uuid= UUID.randomUUID().toString();
        //存放到redis中 "captcha:"+uuid
        String redisKey= RedisConstant.CAPTCHA_KEY+ uuid;
        this.redisTemplate.opsForValue().set(redisKey, value,RedisConstant.CAPTCHA_EXPIRED_MINUTES, TimeUnit.MINUTES);

        //返回
        CaptchaCodeResp resp=new CaptchaCodeResp();
        resp.setUuid(uuid);
        resp.setImage(captcha.toBase64());

        return R.success(resp);
    }

}
